/*
 * @Author       : Sayolit
 * @Date         : 2023-01-08 12:15:44
 * @LastEditors  : Sayolit
 * @LastEditTime : 2023-03-07 15:10:17
 * @FilePath     : request.js
 * @Description  :
 * Copyright 2023 Sayolit, All Rights Reserved.
 * 2023-01-08 12:15:44
 */
import axios from 'axios'
import { ElMessage } from 'element-plus'
import storage from './storage'
import NProgress from 'nprogress' // 引入nprogress插件
import 'nprogress/nprogress.css' // 这个nprogress样式必须引入

//设置全局的axios的配置
const service = axios.create({
	baseURL: '/api',
	timeout: 4000,
	// headers: {
	// 	Accept: 'application/json',
	// 	'Content-Type': 'application/json',
	// },
})

/*配置请求的拦截*/
service.interceptors.request.use(
	function (config) {
		NProgress.start()
		const headers = config.headers
		// console.log(headers)
		//storage中获得token的信息
		//{username: 'admin', roles: 'admin', token: ''}
		const { token = null } = storage.getItem('userInfo') || {}
		//给请求上加上token验证

		// 有token设置authorization并且存入localstorage
		if (token != null) {
			headers.authorization = 'Bearer ' + token

			// 剥离出来单独的token,方便设置过期
			storage.setItem('token', token)
		}
		// 无token清除authorization
		else {
			delete headers.authorization
		}
		return config
	},
	function (error) {
		return Promise.reject(error)
	}
)

/*定义响应拦截*/
service.interceptors.response.use(
	(response) => {
		NProgress.done()
		if (response.status === 200) {
			const { message, code, data } = response
			// console.log(response)
			return data
		}
		//解构赋值，从data中解构出需要的数据字段
	},
	(error) => {
		const code = error.response.status
		switch (code) {
			case 401:
				console.log('无权访问')
				router.push({ path: '/login' })
				break
			case 402:
				ElMessage.error('用户名或密码错误')
				// router.push({ path: '/login' })
				break
			case 403:
				console.log('token过期啦')
				router.push({ path: '/login' })
				break
			case 404:
				console.log('404 NOT FOUND')
				//需要先去配好路由
				router.push({ path: '/404' })
				break
			default:
				console.log(code)
				return Promise.reject(error)
		}
	}
)

//request({method:'post',url:"/user/list",data:[id:1]])
//request({method:'Get',url:"/user/list",data:[id:1}})
function request(options) {
	//定义提交的方式,默认为get
	options.method = options.method || 'get'
	if (options.method.toLowerCase() === 'get') {
		options.params = options.data
	}
	if (options.method.toLowerCase() === 'post') {
	}
	return service(options)
}

//封装get,post,put   request.get(url,data,options)request.post(url,data,options)
;['get', 'post', 'put', 'delete', 'patch'].forEach((item) => {
	request[item] = (url, data, options) => {
		return request({ method: item, url, data, ...options })
	}
})
export default request
